package com.pdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pdp.dto.Result;
import com.pdp.entity.CacheClient;
import com.pdp.entity.RedisData;
import com.pdp.entity.Shop;
import com.pdp.mapper.ShopMapper;
import com.pdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.Transient;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {

        // 解决缓存穿透
//        Shop shop = (Shop) cacheClient
//                .queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);


        // 互斥锁解决缓存击穿
        // Shop shop = queryWithMutex(id);

        // 逻辑过期解决缓存击穿
        // Shop shop = queryWithLogicalExpire(id);
        Shop shop = (Shop) cacheClient
                .queryWithLogicalExpire(RedisConstants.CACHE_SHOP_KEY, id, Shop.class, this::getById, RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);


        if(shop == null) {
            return Result.fail("店铺不存在");
        }
        // 返回
        return Result.ok(shop);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public Shop queryWithLogicalExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        // 1.从redis查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.判断是否命中
        if(StrUtil.isBlank(shopJson)){
            // 未命中
            return null;
        }
        // 3.命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        // 4.判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            // 4.1. 未过期，直接返回店铺信息
            return shop;
        }
        // 4.2. 已过期，需要缓存重建
        // 5.缓存重建
        // 5.1. 获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        // 5.2. 判断是否获取成功
        if(isLock) {
            /*
            如果在一个线程尝试获得锁之前（还没有去获得锁），
            另一个线程正好释放锁。
            那这个线程得到锁之后还会有一次缓存重建，所以双重检查是必须的，
             */
            // 再次判断是否过期
            RedisData redisData1 = JSONUtil.toBean(shopJson, RedisData.class);
            Shop shop1 = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
            LocalDateTime expireTime1 = redisData.getExpireTime();
            if(expireTime1.isAfter(LocalDateTime.now())){
                return shop1;
            }

            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    // 重建缓存
                    // 此时20s，只是为了测试方便，以后还要改成30min
                    this.saveShop2Redis(id, 20L);
                } catch(Exception e) {
                    throw new RuntimeException(e);
                }finally{
                    // 释放锁
                    unlock(lockKey);
                }
            });
        }

        return shop;
    }

    public Shop queryWithMutex(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 从Redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            // 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }

        // 判断命中的是否是空值
        if(shopJson != null) {
            // 返回一个错误信息
            return null;
        }

        // 实现缓存重建
        // 1.获取互斥锁
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            // 2.判断是否获取成功
            if(!isLock){
                // 3.失败，则休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }

            // 4.成功，根据id查询数据库
            shop = getById(id);

            // 模拟重建的延时
            Thread.sleep(200);

            // 数据库不存在，返回错误
            if(shop == null){
                // 将空值写入redis
                // 产生一个随机数，防止缓存雪崩
                int rand = (int)Math.random() * 20;
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL + rand, TimeUnit.MINUTES);
                // 返回错误信息
                return null;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放互斥锁
            unlock(lockKey);
        }

        // 数据库存在，写回Redis，设置过期时间
        // 产生一个随机数，防止缓存雪崩
        int rand = (int)Math.random() * 20;
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL + rand, TimeUnit.MINUTES);
        // 返回
        return shop;
    }

    // 缓存穿透和缓存雪崩
    public Shop queryWithPassThrough(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 从Redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
            // 存在，直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            //return Result.ok(shop);
            return shop;
        }

        // 判断命中的是否是空值
        if(shopJson != null) {
            // 返回一个错误信息
            return null;
            //return Result.fail("店铺信息不存在!");
        }

        // 不存在，根据id查询数据库
        Shop shop = getById(id);
        // 数据库不存在，返回错误
        if(shop == null){
            // 将空值写入redis
            // 产生一个随机数，防止缓存雪崩
            int rand = (int)Math.random() * 20;
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL + rand, TimeUnit.MINUTES);
            // 返回错误信息
            //return Result.fail("店铺不存在");
            return null;
        }
        // 数据库存在，写回Redis，设置过期时间
        // 产生一个随机数，防止缓存雪崩
        int rand = (int)Math.random() * 20;
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY+id, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL + rand, TimeUnit.MINUTES);
        // 返回
        //return Result.ok(shop);
        return shop;
    }

    // 尝试锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    // 释放锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        // Thread.sleep(20);
        //1.查询店铺数据
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transient
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空");
        }
        // 1.更新数据库
        updateById(shop);
        // 2.删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
